package example.NIOTCPTest;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;

public class InteractiveClient {
    private static Charset charset = Charset.forName("UTF-8");
    
    public static void main(String[] args) throws Exception {
        SocketChannel client = SocketChannel.open();
        client.connect(new InetSocketAddress("localhost", 8888));
        System.out.println("已连接到服务器，请输入消息 (输入 'quit' 退出):");
        
        Scanner scanner = new Scanner(System.in);
        String input;
        
        while (true) {
            System.out.print("> ");
            input = scanner.nextLine();
            
            if ("quit".equalsIgnoreCase(input)) {
                break;
            }
            
            sendMessage(client, input);
            receiveResponse(client);
        }
        
        client.close();
        scanner.close();
        System.out.println("连接已关闭");
    }
    
    private static void sendMessage(SocketChannel client, String message) throws Exception {
        byte[] messageData = message.getBytes(charset);
        ByteBuffer buffer = ByteBuffer.allocate(4 + messageData.length);
        
        buffer.putInt(messageData.length);
        buffer.put(messageData);
        buffer.flip();
        
        while (buffer.hasRemaining()) {
            client.write(buffer);
        }
    }
    
    private static void receiveResponse(SocketChannel client) throws Exception {
        ByteBuffer lengthBuffer = ByteBuffer.allocate(4);
        
        // 读取长度头
        while (lengthBuffer.hasRemaining()) {
            client.read(lengthBuffer);
        }
        lengthBuffer.flip();
        int responseLength = lengthBuffer.getInt();
        
        // 读取响应体
        ByteBuffer responseBuffer = ByteBuffer.allocate(responseLength);
        while (responseBuffer.hasRemaining()) {
            client.read(responseBuffer);
        }
        responseBuffer.flip();
        
        String response = charset.decode(responseBuffer).toString();
        System.out.println("服务器: " + response);
    }
}